#include "stdafx.h"
#include "resource.h"
#include <xcommonfunc.h>
#include <Xmemdc.h>
#include "XmlParse.h"
#include "XDialogImpl.h"


#define TITLEBAR_HEIGHT		20

CXDialogImpl::CXDialogImpl(void) : m_pXmlParse(NULL), m_pBackPng(NULL), m_pBackLayer(NULL)
{
	for (int i = 0; i < DEFAULT_BUTTON_COUNT; ++i)
	{
		m_pButtons[i] = NULL;
	}
}

CXDialogImpl::~CXDialogImpl(void)
{
	for (int i = 0; i < DEFAULT_BUTTON_COUNT; ++i)
	{
		if (m_pButtons[i] != NULL)
		{
			delete m_pButtons[i];
			m_pButtons[i] = NULL;
		}
	}
}
BOOL WINAPI EnumWindowProc(HWND hWnd, LPARAM lParam)
{
	CXDialogImpl * pDlg = (CXDialogImpl * )lParam;
	static int nIndex = 0;
	TCHAR szClassName[256] = {0};
	::GetClassName(hWnd, szClassName, 255);
	if(0 == _tcscmp(szClassName, _T("Button")))
	{
		pDlg->m_pButtons[nIndex] = new CXPngButton();
		pDlg->m_pButtons[nIndex]->SubclassWindow(hWnd);
		pDlg->m_pButtons[nIndex]->SetButtonPng(pDlg->m_strConfigPath + _T("\\") + pDlg->m_pXmlParse->m_strButton, pDlg->m_pXmlParse->m_nButtonNum);
		++nIndex;
	}
	return TRUE;
}


LRESULT CXDialogImpl::OnInitDialog(HWND hWnd, LPARAM lParam)
{
	CRect rect;
	GetClientRect(&rect);

	GetConfigPath();
	m_pXmlParse = new CXmlParse(m_strConfigPath + _T("\\config.xml"));
	m_pXmlParse->LoadAllParam();

	EnumChildWindows(m_hWnd, EnumWindowProc, (LPARAM)this);

	CWindow window = ::GetDlgItem(hWnd, IDC_TITLEBAR);
	if (!window.m_hWnd)
	{
		CRect rectTitle(rect);
		rectTitle.bottom = rectTitle.top + TITLEBAR_HEIGHT;
		m_TitleBar.Create(m_hWnd, rectTitle);

		m_TitleBar.SetTitleText(CString(MAKEINTRESOURCE(IDS_TITLE)), m_pXmlParse->m_colorTitleText);
		m_TitleBar.AddButton(ID_CUSTOM_CLOSE_BUTTON, m_strConfigPath + _T("\\") + m_pXmlParse->m_strTitleClose, m_pXmlParse->m_nCloseButtonNum);	
	}	
	
	m_pBackPng = NewImageObject(m_pXmlParse->m_strBackground);
	if (m_pBackPng)
	{
		m_pBackPng->LoadImageFile(m_strConfigPath + _T("\\") + m_pXmlParse->m_strBackground);
	}

	m_pBackLayer = NewImageObject(m_pXmlParse->m_strLayer);
	if (m_pBackLayer)
	{
		m_pBackLayer->LoadImageFile(m_strConfigPath + _T("\\") + m_pXmlParse->m_strLayer);
	}	

	SetWindowText(CString(MAKEINTRESOURCE(IDS_TITLE)));

	return 1;
}

LRESULT CXDialogImpl::OnEraseBkgnd(HDC)
{
	return TRUE;
}

LRESULT CXDialogImpl::OnPaint(HDC hdc)
{
	CRect rect;
	GetClientRect(&rect);

	CXMemDC memDC(hdc, rect);

	::PatBlt(memDC.m_hDC, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, WHITENESS);
	if (m_pBackPng)
	{
		rect.right--;
		rect.bottom--;
		m_pBackPng->FillRectWithImage(memDC.m_hDC, rect, 100);
	}
	if (m_pBackLayer)
	{
		m_pBackLayer->StretchImage_Full(memDC.m_hDC, rect, 100);
	}
	return TRUE;
}


void CXDialogImpl::GetConfigPath()
{
	m_strConfigPath = GetAbsolutePath(NULL);
	m_strConfigPath += _T("\\Config");
}